<?php
/**
 * Created by Administrator
 * User: longli
 * VX: isa1589518286
 * Date: 2020/12/23
 * Time: 19:24
 * @link http://www.lmterp.cn
 */

namespace app\common\service\import;

use app\common\library\Tools;
use app\common\model\ChannelExpress;
use app\common\model\JobFlowModule;
use app\common\model\Purchase;
use app\common\service\purchase\PurchaseService;

/**
 * 上传采购追踪号
 * Class PurchaseTrack
 * @package app\common\service\import
 */
class PurchaseTrack extends BaseImport
{

    private $field = [
        '采购单号'    => 'purchase_sn',
        '供应商单号'  => 'producer_sn',
        '物流公司'    => 'logistics_name',
        '追踪号'      => 'track_num',
        '包裹重量'    => 'weight',
        '包裹明细'    => 'info',
        '备注'       => 'remark',
    ];

    protected function write()
    {
        $trackData = Tools::sortArray($this->getData(), 'purchase_sn');
        foreach($trackData as $track)
        {
            $this->transform($track);
            $pur = Purchase::getBySn($track['purchase_sn']);
            // 供应商单号
            if(!empty($track['producer_sn']))
            {
                $pur->producer_sn = trim($track['producer_sn']);
                $pur->save();
            }
            $info = $track['info'];
            if(empty($info))
            {
                $info = [];
                foreach($pur->info as $item)
                {
                    $info[] = [
                        'sku' => $item->sku,
                        'qty' => $item->n_store_qty,
                    ];
                }
            }
            if(!PurchaseService::getInstance()->addTrack($pur, $track, $info)) return false;
        }
        return true;
    }

    protected function validate(&$row = [], $key = 0)
    {
        $error = [];
        $validate = array_flip($this->field);
        $row = Tools::replaceArrayKey($this->field, $row);
        if(($req = $this->requireField($row, ['purchase_sn', 'track_num'], $validate)) !== true) $error = array_merge($error, $req);
        if(!Purchase::hasPurchase($row['purchase_sn'])) $error[] = "采购单【{$row['purchase_sn']}】不存在";
        if(!ChannelExpress::hasName($row['logistics_name'])) $error[] = "快递公司【{$row['logistics_name']}】不存在，请先录入";
        $purchase = Purchase::getBySn($row['purchase_sn']);
        if(!JobFlowModule::isCheckFinish($purchase)) $error[] = "采购单【{$row['purchase_sn']}】未审批通过";
        $row['pay_type'] = $purchase->logistics_price == 0 ? \app\common\model\PurchaseTrack::PAY_TYPE_T : \app\common\model\PurchaseTrack::PAY_TYPE_M;
        if(empty($row['weight'])) $row['weight'] = 0;
        if(($num = $this->validateNumber($row, ['weight'], $validate)) !== true) $error = array_merge($error, $num);
        if(!empty($row['info']) && ($valiInfo = $this->validateSku($row)) !== true) $error[] = $valiInfo;
        return !empty($error) ? join(", ", $error) : true;
    }

    /**
     * 验证 SKU 是否属于当前采购单
     * @param array $row 当前行数据
     * @return bool|string
     * @date 2020/12/23
     * @author longli
     */
    protected function validateSku(& $row = [])
    {
        $infos = str_replace(['：', '，'], [':', ','], $row['info']);
        $infos = explode(",", $infos);
        $skus = $info = [];
        foreach($infos as $s)
        {
            if(!Tools::contains($s, ":")) return "【$s}】格式不正确定";
            list($sku, $qty) = explode(':', $s);
            $skus[] = $sku;
            $info[] = compact('sku', 'qty');
        }
        $row['info'] = $info;
        if(($diff = Purchase::get(['purchase_sn' => $row['purchase_sn']])->isHasSku($skus)) !== true)
            return sprintf("【%s】不属于采购单【%s】", join(', ', $diff), $row['purchase_sn']);
        return true;
    }

    protected function transform(&$row = [])
    {
        $row['express_id'] = ChannelExpress::where([
            'logistics_name' => $row['logistics_name']
        ])->value('express_id');
    }
}